const { Pet } = require('../models');
const { getHoursDifference } = require('../utils/dateTime');

class PetService {
    async createPet(petData) {
        if (!petData.name || !petData.species || !petData.appearance) {
            throw new Error('Missing required pet information');
        }
        return await Pet.create(petData);
    }

    async getPetById(petId, userId) {
        const pet = await Pet.findOne({
            where: {
                id: petId,
                userId: userId
            }
        });
        if (!pet) {
            throw new Error('Pet not found');
        }
        return pet;
    }

    async getUserPets(userId) {
        return await Pet.findAll({
            where: { userId }
        });
    }

    async feedPet(petId, userId) {
        const pet = await this.getPetById(petId, userId);
        
        const hoursSinceLastFeed = pet.lastFed ? 
            getHoursDifference(new Date(), pet.lastFed) : 24;

        if (hoursSinceLastFeed < 4) {
            throw new Error('Pet was recently fed');
        }

        pet.hunger = Math.min(100, pet.hunger + 20);
        pet.happiness = Math.min(100, pet.happiness + 10);
        pet.lastFed = new Date();
        
        await pet.save();
        return pet;
    }

    async trainPet(petId, userId) {
        const pet = await this.getPetById(petId, userId);
        
        // 只检查体力和饥饿值要求，不设置冷却时间限制
        if (pet.energy < 10) {
            throw new Error('宠物体力不足，无法训练');
        }

        if (pet.hunger < 5) {
            throw new Error('宠物太饿了，无法训练');
        }

        // 更新宠物状态
        pet.energy = Math.max(0, pet.energy - 10);  // 消耗10%体力
        pet.hunger = Math.max(0, pet.hunger - 5);   // 消耗5%饥饿值
        pet.happiness = Math.min(100, pet.happiness + 3);     // 增加3%心情
        
        // 增加经验
        pet.experience += 10;  // 获得10点经验
        if (pet.experience >= 100) {
            pet.level += 1;
            pet.experience = 0;
        }
        
        // 记录训练时间，但不用于冷却检查
        pet.lastTrained = new Date();
        await pet.save();
        return pet;
    }

    async mintPetNFT(petId, userId, tokenId) {
        const pet = await this.getPetById(petId, userId);
        
        if (pet.isNFT) {
            throw new Error('Pet is already an NFT');
        }

        pet.isNFT = true;
        pet.tokenId = tokenId;
        await pet.save();
        return pet;
    }

    async updatePetStats(petId, userId, stats) {
        const pet = await this.getPetById(petId, userId);
        
        // 更新宠物状态
        if (stats.hunger !== undefined) pet.hunger = stats.hunger;
        if (stats.happiness !== undefined) pet.happiness = stats.happiness;
        if (stats.energy !== undefined) pet.energy = stats.energy;
        
        await pet.save();
        return pet;
    }

    async autoRecoverEnergy(petId, userId) {
        const pet = await this.getPetById(petId, userId);
        
        // 如果体力值小于100，每10秒恢复5%
        if (pet.energy < 100) {
            pet.energy = Math.min(100, pet.energy + 5);
            await pet.save();
        }
        
        return pet;
    }
}

module.exports = new PetService();